package cn.elead.chaos.email.autoconfigure;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import cn.elead.chaos.email.controller.MailController;
import cn.elead.chaos.email.handler.DefaultSendHandler;
import cn.elead.chaos.email.handler.ISendHandler;
import cn.elead.chaos.email.mail.CustomJavaMailSenderImpl;
import cn.elead.chaos.email.service.IEmailService;
import cn.elead.chaos.email.service.ISubjectAttachService;
import cn.elead.chaos.email.service.impl.DefaultSubjectAttachService;
import cn.elead.chaos.email.service.impl.EmailService;
import cn.elead.chaos.email.template.TemplateProcess;
import cn.elead.chaos.email.template.freemarker.FreemarkerProcess;

@Configuration
@ComponentScan(basePackageClasses = { MailController.class })
@EnableConfigurationProperties(MailProperties.class)
public class EmailAutoConfiguration {

	/**
	 * 邮件发送服务
	 * 
	 * @param properties
	 * @return
	 */
	@Bean
	public JavaMailSenderImpl javaMailSenderImpl(MailProperties properties) {
		return new CustomJavaMailSenderImpl(properties);
	}

	/**
	 * Velocity模板引擎
	 * 
	 * @return
	 */
	/*@Bean
	public VelocityEngine velocityEngine() {
		VelocityEngine engine = new VelocityEngine();
		engine.init();
		return engine;
	}*/

	/**
	 * 邮件模板处理
	 * 
	 * @return
	 */
	@Bean
	@Scope(scopeName = ConfigurableBeanFactory.SCOPE_SINGLETON)
	public TemplateProcess templateProcess() {
		//VelocityProcess process = new VelocityProcess();
		FreemarkerProcess process = new FreemarkerProcess();
		return process;
	}

	/**
	 * 邮件服务
	 * 
	 * @return
	 */
	@Bean
	public IEmailService emailService() {
		return new EmailService();
	}

	/**
	 * 默认模板和附件服务
	 * 
	 * @return
	 */
	@Bean
	@ConditionalOnMissingBean(ISubjectAttachService.class)
	public ISubjectAttachService subjectAttachService() {
		return new DefaultSubjectAttachService();
	}

	/**
	 * 默认邮件发送成功失败处理器
	 * 
	 * @return
	 */
	@Bean
	@ConditionalOnMissingBean(ISendHandler.class)
	public ISendHandler sendHandler() {
		return new DefaultSendHandler();
	}
}
